/*
    Copyright (C) 2022 Tenable, Inc.

	Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

		http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

package vulnerability

import (
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"

	"github.com/tenable/terrascan/pkg/iac-providers/output"
	"go.uber.org/zap"
)

const (
	registryUsername         = "HARBOR_REGISTRY_USERNAME"
	registryPassword         = "HARBOR_REGISTRY_PASSWORD"
	vulnerabilityHeader      = "X-Accept-Vulnerabilities"
	vulnerabilityHeaderValue = "application/vnd.scanner.adapter.vuln.report.harbor+json; version=1.0"
	skipTLSVerify            = "HARBOR_SKIP_TLS"
	certificate              = "HARBOR_REGISTRY_CACERT"
	registryDomain           = "HARBOR_REGISTRY_DOMAIN"
)

// ServerCaller interface with client methods
type ServerCaller interface {
	Do(req *http.Request) (*http.Response, error)
}

// harborScanner holds external harbor registry methods
type harborScanner interface {
	prepareRequest(serverURL string) (*http.Request, error)
	sendRequest(caller ServerCaller, req *http.Request) ([]byte, error)
	getClient() *http.Client
}

// scanner implementor for harborScanner interface
type hscanner struct{}

// Harbor  Harbor container registry
type Harbor struct {
	scanner harborScanner
}

func init() {
	RegisterContainerRegistry("harbor", &Harbor{
		scanner: hscanner{},
	})
}

// prepareRequest prepares http request
func (hscanner) prepareRequest(serverURL string) (*http.Request, error) {
	username := os.Getenv(registryUsername)
	password := os.Getenv(registryPassword)

	if username == "" || password == "" {
		errorMsg := fmt.Errorf("incomplete authentication details")
		zap.S().Error(errorMsg)
		return nil, errorMsg
	}

	req, err := http.NewRequest(http.MethodGet, serverURL, nil)
	if err != nil {
		errorMsg := fmt.Errorf("error creating harbor server request: %v", err)
		zap.S().Error(errorMsg)
		return nil, errorMsg
	}

	req.Header.Add("accept", "application/json")
	req.Header.Add(vulnerabilityHeader, vulnerabilityHeaderValue)

	req.SetBasicAuth(username, password)

	return req, nil
}

// getClient prepares http client
func (hscanner) getClient() *http.Client {
	tlsConfig := &tls.Config{}

	skipTLS := os.Getenv(skipTLSVerify)
	if skipTLS != "" {
		if strings.EqualFold(skipTLS, "true") {
			tlsConfig.InsecureSkipVerify = true
		}
	}

	cert := os.Getenv(certificate)
	if cert != "" {
		caCert, err := os.ReadFile(cert)
		if err != nil {
			errorMsg := fmt.Errorf("client certificate not found")
			zap.S().Error(errorMsg)
		} else {
			caCertPool := x509.NewCertPool()
			caCertPool.AppendCertsFromPEM(caCert)
			tlsConfig.RootCAs = caCertPool
		}
	}

	return &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: tlsConfig,
		},
	}
}

// sendRequest sends request to harbor
func (hscanner) sendRequest(caller ServerCaller, req *http.Request) ([]byte, error) {
	res, err := caller.Do(req)
	if err != nil {
		errorMsg := fmt.Errorf("error calling harbor server: %v", err)
		zap.S().Error(errorMsg)
		return nil, errorMsg
	}

	defer res.Body.Close()

	body, err := io.ReadAll(res.Body)
	if err != nil {
		errorMsg := fmt.Errorf("error reading response from harbor: %v", err)
		zap.S().Error(errorMsg)
		return nil, err
	}

	if res.StatusCode != http.StatusOK {
		errMsg := fmt.Errorf("error: %s", string(body))
		return nil, errMsg
	}

	return body, nil
}

// CheckRegistry verify provided image belongs to harbor registry
func (h *Harbor) checkRegistry(image string) bool {
	reg := os.Getenv(registryDomain)
	host := GetDomain(image)
	return reg != "" && strings.EqualFold(reg, host)
}

// GetVulnerabilities - get vulnerabilities from harbor registry
func (h *Harbor) getVulnerabilities(container output.ContainerDetails, options map[string]interface{}) (vulnerabilities []output.Vulnerability) {
	results, err := h.ScanImage(container.Image)
	if err != nil {
		zap.S().Errorf("error finding vulnerabilities for image %s : %v", container.Image, err)
		return
	}
	if temp, ok := results[vulnerabilityHeaderValue]; ok {
		if tempData, ok := temp.(map[string]interface{}); ok {
			if tempResults, ok := tempData["vulnerabilities"]; ok {
				mapResults, _ := tempResults.([]interface{})
				for _, result := range mapResults {
					vulnerability := output.Vulnerability{}
					if data, ok := result.(map[string]interface{}); ok {
						vulnerability.PrepareFromHarborImageScan(data)
						vulnerabilities = append(vulnerabilities, vulnerability)
					}
				}
			}
		}
	}

	return
}

// ScanImage get the image scan result from harbor registry
func (h *Harbor) ScanImage(image string) (result map[string]interface{}, err error) {
	imageDetails := ImageDetails{}
	imageDetails = GetImageDetails(image, imageDetails)
	if imageDetails.Tag == "" {
		imageDetails.Tag = defaultTagValue
	}
	reference := imageDetails.Tag
	if imageDetails.Digest != "" {
		reference = imageDetails.Digest
	}

	project, repository := getProjectNameAndRepository(imageDetails.Repository)

	serverURL := fmt.Sprintf("https://%s/api/v2.0/projects/%s/repositories/%s/artifacts/%s/additions/vulnerabilities",
		imageDetails.Registry,
		project,
		repository,
		reference)

	client := h.scanner.getClient()

	req, err := h.scanner.prepareRequest(serverURL)
	if err != nil {
		return nil, err
	}

	data, err := h.scanner.sendRequest(client, req)
	if err != nil {
		return nil, err
	}

	if err := json.Unmarshal(data, &result); err != nil {
		errorMsg := fmt.Errorf("error unmarshaling harbor server response : %v", err)
		zap.S().Error(errorMsg)
		return nil, errorMsg
	}
	return result, nil
}

// getProjectNameAndRepository fetch project and repo name
func getProjectNameAndRepository(name string) (string, string) {
	parts := strings.Split(name, "/")
	if len(parts) >= 2 {
		return parts[0], parts[1]
	}
	return "", ""
}
